<template>
	<view>
		<view class="cu-list menu border">
			<view class="cu-item" :class="menuArrow ? 'arrow' : ''">
				<view class="content">文件上传</view>
				<view class="action" @tap.stop="chooseFile()">
					<button class="cu-btn round shadow text-white" :style="{backgroundColor:theme}">
						<text class="cuIcon-upload"></text>
						上传
					</button>
				</view>
			</view>
			<view v-for="(item, ind) in fileList" :key="ind" class="cu-item" :class="menuArrow ? 'arrow' : ''">
				<view class="content" style="overflow: hidden;text-overflow: ellipsis;">
					<text class="text-grey">
						<text class="cuIcon-tagfill text-red  margin-right-xs"></text>
						{{ item.fileName }}
					</text>
				</view>
				<view class="action">
					<!-- #ifdef APP-PLUS || MP-WEIXIN -->
					<view class="cu-tag round bg-blue light" @tap.stop="ViewFile" :data-url="item.fileUrl">预览</view>
					<!-- #endif -->
					<!-- #ifdef H5 -->
						<view class="cu-tag round bg-olive light" @tap.stop="downLoad" :data-url="item.fileUrl">下载</view>
					<!-- #endif -->
					<view class="cu-tag round bg-red light" @tap.stop="DelFile(index, ind)" :data-index="ind">删除</view>
				</view>
			</view>
		</view>
		<input type="text" :name="bizType" :value="fileListStr" hidden>
		<input type="text" :name="fileDel" :value="fileDelListStr" hidden>
		<l-file ref="lFile" @up-success="upSuccess"></l-file>
		<view ref="input" class="input" hidden="true"></view>
	</view>
</template>
<script>
	import {
		mapState
	} from 'vuex'
	export default {
		name: 'js-input',
		behaviors: ['uni://form-field-group'],
		data() {
			return {
				// 文件列表
				fileList: [],
				needDel: []
			};
		},
		props:{
			bizType: {
				type: String,
				default: ''
			},
			fileDel: {
				type: String,
				default: ''
			},
			bizKey: {
				type: String,
				default: ''
			}
		},
		computed: {
			...mapState(["theme", "HOST_URL", "__sid"]),
			fileListStr(){
				// 需要上传的图片
				let files = []
				this.fileList.forEach((v, k)=>{
					files.push(v.id)
				})
				return files.join(",")
			},
			fileDelListStr(){
				// 需要删除的图片
				return this.needDel.join(",")
			}
		},
		mounted() {
			// H5端文件上传
			// #ifdef H5
			var that = this;
			var input = document.createElement('input');
			input.type = 'file';
			input.id = 'fileAll';
			input.style.display = 'none';
			input.onchange = event => {
				that.uploadFileH5();
			};
			this.$refs.input.$el.appendChild(input);
			// #endif
			// 显示默认的文件
			if(this.bizKey){
				uni.showLoading({
					title: '文件加载中',
					mask: false
				});
				this.$request({
					url: "a/file/fileList",
					data: {
						bizKey: this.bizKey,
						bizType: this.bizType
					},
					success:(res)=>{
						if(res.data.length){
							res.data.forEach((v, k)=>{
								console.log(this.HOST_URL + v.fileUrl)
								v.fileUrl = this.HOST_URL + v.fileUrl;
							})
							this.fileList = this.fileList.concat(res.data)
						}
						uni.hideLoading()
					}
				})
			}
		},
		methods: {
			// 选择文件
			chooseFile() {
				// #ifdef H5
				document.getElementById('fileAll').click();
				// #endif
				// #ifdef MP-WEIXIN || APP-PLUS
				let host = this.HOST_URL
				let that = this
				this.$refs.lFile.upload({
					// #ifdef APP-PLUS
					// nvue页面使用时请查阅nvue获取当前webview的api，当前示例为vue窗口
					currentWebview: this.$mp.page.$getAppWebview(),
					// #endif
					//非真实地址，记得更换,调试时ios有跨域，需要后端开启跨域并且接口地址不要使用http://localhost/
					url: host + 'a/file/upload?__sid=' + that.__sid,
					//默认file,上传文件的key
					name: 'file'
				});
				// #endif
			},
			// 文件上传成功
			upSuccess(data){
				// #ifdef APP-PLUS
				let result = JSON.parse(data.data.id);
				let that = this;
				if (result.result == 'true') {
					result.fileUpload.fileUrl = that.HOST_URL + result.fileUpload.fileUrl;
					var obj = {};
					obj.id = result.fileUpload.id;
					obj.fileUrl = result.fileUpload.fileUrl;
					obj.fileName = result.fileUpload.fileName;
					that.fileList.push(obj);
				} else {
					uni.showModal({
						title: '提示',
						content: result.message,
						showCancel: false,
						cancelText: '',
						confirmText: '确定',
						success: res => {},
						fail: () => {},
						complete: () => {}
					});
				}
				// #endif
				// #ifdef MP-WEIXIN
				let result = data.data;
				console.log(result)
				let that = this;
				if (result.result == 'true') {
					result.fileUpload.fileUrl = that.HOST_URL + result.fileUpload.fileUrl;
					var obj = {};
					obj.id = result.fileUpload.id;
					obj.fileUrl = result.fileUpload.fileUrl;
					obj.fileName = result.fileUpload.fileName;
					that.fileList.push(obj);
				} else {
					uni.showModal({
						title: '提示',
						content: result.message,
						showCancel: false,
						cancelText: '',
						confirmText: '确定',
						success: res => {},
						fail: () => {},
						complete: () => {}
					});
				}
				// #endif
			},
			// 下载文件
			downLoad(e) {
				let filePath = e.currentTarget.dataset.url;
				// #ifdef H5
				uni.showModal({
					title: '',
					content: '确定要下载么？下载文件可能会关闭该程序',
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						if (res.confirm) {
							window.open(filePath);
						}
					}
				});
				// #endif
			},
			// H5文件上传
			uploadFileH5() {
				// #ifdef H5
				uni.showLoading({
					title: '上传中...',
					mask: false
				});
				var fData = new FormData();
				var index1 = document.getElementById('fileAll').value.lastIndexOf('.');
				var index2 = document.getElementById('fileAll').value.length;
				var suffix = document.getElementById('fileAll').value.substring(index1, index2); //后缀名
				fData.append('file', document.getElementById('fileAll').files[0]);
				fData.append('fileMd5', new Date().getTime() + this.__sid);
				fData.append('bizKey', '');
				fData.append('bizType', "testData_image");
				fData.append('uploadType', 'all');
				fData.append('fileName', document.getElementById('fileAll').files[0].name);
				fData.append('id', 'WU_FILE_0');
				fData.append('name', new Date().getTime());
				//fData.append('type', 'image/' + suffix.replace('.', ''));
				fData.append('size', document.getElementById('fileAll').size);
				var xhr = new XMLHttpRequest();
				xhr.open('POST', this.HOST_URL + '/a/file/upload?__ajax=json&__sid=' + this.__sid, true);
				let that = this;
				xhr.onreadystatechange = function() {
					console.log(xhr.readyState);
					if (xhr.readyState == 4) {
						var result = JSON.parse(xhr.responseText);
						if (result.result == 'true') {
							result.fileUpload.fileUrl = that.HOST_URL + result.fileUpload.fileUrl;
							var obj = {};
							obj.id = result.fileUpload.id;
							obj.fileUrl = result.fileUpload.fileUrl;
							obj.fileName = result.fileUpload.fileName;
							that.fileList.push(obj);
							document.getElementById('fileAll').value = '';
							uni.hideLoading()
						}else {
							uni.showModal({
								title: '提示',
								content: result.message,
								showCancel: false,
								cancelText: '',
								confirmText: '确定',
								success: res => {},
								fail: () => {},
								complete: () => {}
							});
						}
					}
				};
				//上传成功
				xhr.send(fData);
				// #endif
			},
			// 文件预览
			ViewFile(e) {
				let filePath = e.currentTarget.dataset.url;
				console.log(filePath);
				// #ifdef APP-PLUS || MP-WEIXIN
				// filePath = 'http://demo.jeesite.com/js/userfiles/fileupload/201907/1148170743879204866.doc';
				/* 预览临时文件 */
				this.$refs.lFile.download(filePath).then(path => {
					this.$refs.lFile.open(path);
				});
				// #endif
				// #ifdef H5
				uni.navigateTo({
					url: '/components/js-view/js-view?url=' + filePath,
					animationType: 'zoom-out'
				});
				// #endif
			},
			// 文件删除
			DelFile(index, ind) {
				uni.showModal({
					title: '',
					content: '确定要删除吗？',
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						if (res.confirm) {
							let obj = this.fileList.splice(ind, 1);
							this.needDel.push(obj[0].id);
						}
					}
				});
			}
		}
	}
</script>
<style>

</style>
